<template>
  <cu-layout :navProp="{ placeholder: true, title: '支付方式', textColor: 'black', bgColor: 'rgba(255,255,255,1)' }">
    <view :class="[`${prefixCls}-payment-container`]">
      <view class="bill-detail">
        <!-- 支付金额 -->
        <view class="bill-detail-title">待支付账单总额</view>
        <view class="bill-detail-price"><text>￥</text>{{ amount || 0 }}</view>

        <!-- 支付状态说明 -->
        <view class="bill-detail-time">
          <!-- <text v-if="[-2, 2].includes(payStatus)">{{ payStatus === -2 ? '未查询到支付单信息' : payStatus === 2 ? '该订单已支付' : '' }}</text> -->
          <!-- <uv-count-down :time="30 * 60 * 60 * 1000" format="HH:mm:ss" v-else-if="payStatus === 1" @change="onChangePayCountDown"></uv-count-down> -->
        </view>
      </view>

      <!-- 支付方式 -->
      <view class="payment-method">
        <uv-radio-group v-model="payment" placement="column" iconPlacement="right">
          <uv-radio v-for="(item, index) in payMethods" :key="index" :name="item.payment_channel_value" :label="item.payment_channel_name" :activeColor="theme">
            <view class="payment-method-item">
              <image :src="item.payment_channel_icon"></image>
              <text>{{ item.payment_channel_name }}</text>
            </view>
          </uv-radio>
        </uv-radio-group>
      </view>

      <!-- 支付操作 -->
      <view class="payment-btn" :style="{ bottom: 0, paddingBottom: `${$Platform.device.safeAreaInsets.bottom + 20}rpx` }">
        <uv-button type="primary" size="large" :disabled="payStatus !== 1" :loading="payLoading" @click="handlePayment" :text="payButtonText"></uv-button>
      </view>
    </view>
  </cu-layout>
</template>

<script>
import { billReceiptZreo, getPayChannel } from '@/api/payment'
import { AuthError } from '@/common/request/helper'
import { mapActions, mapGetters } from 'vuex'
export default {
  name: 'payment',
  components: {},
  mixins: [],
  props: {},
  data() {
    return {
      payment: '', // 选择的支付方式
      scene: '', // 订单业务类型
      amount: 0, // 订单支付金额
      // 预支付订单参数
      orderInfo: {
        paymentMethod: '',
        // ... 其他参数
      },
      payStatus: 0, // 支付状态  0=检测支付环境， 1=待支付，2=支付中
      payLoading: false,
      // 可用的支付方式
      payMethods: [
        // {
        //   payment_channel: 'wx',
        //   payment_channel_icon: 'https://boyu-new.oss-cn-shenzhen.aliyuncs.com/platform/pay_icon/icon_WeChat.png',
        //   payment_channel_name: '微信支付',
        //   payment_channel_value: 'wechat',
        // },
        // {
        //   payment_channel: 'al',
        //   icon: 'https://boyu-new.oss-cn-shenzhen.aliyuncs.com/platform/pay_icon/icon_Alipay.png',
        //   payment_channel_name: '支付宝支付',
        //   payment_channel_value: 'alipay',
        // },
      ],
    }
  },
  // 侦听属性
  watch: {},
  // 计算属性
  computed: {
    ...mapGetters(['theme', 'token', 'DefEnvCon']),

    // 支付按钮文本
    payButtonText() {
      let text = ''
      const status = this.payStatus
      switch (status) {
        case 0:
          text = '支付环境检测中'
          this.payLoading = true
          break
        case 1:
          // #ifdef APP-PLUS
          text = '去支付'
          // #endif

          // #ifndef APP-PLUS
          text = '确认支付'
          // #endif
          this.payLoading = false
          break
        case 2:
          text = '支付中'
          this.payLoading = true
          break
      }
      return text
    },
  },
  // 监听页面加载，该钩子被调用时data,computed,function,watch,props,slots已设置完成
  onLoad(options) {
    // 设置APP初始化信息 APP来源的话需要设置token免登录
    if (options.token) this.SetAppInitInfo()

    this.setData(options)
    this.getData()
  },
  // 监听页面显示，页面每次出现在屏幕上都触发
  onShow() {},
  // 监听页面初次渲染完成，此时组件已挂载完成
  onReady() {},
  // 下拉刷新
  onPullDownRefresh() {},
  // 加载更多
  onReachBottom() {},

  created() {},
  mounted() {},
  destroyed() {},
  methods: {
    ...mapActions('app', ['SetAppInitInfo']),

    // 订单支付倒计时变化
    onChangePayCountDown(e) {
      console.log('🚀 ~ onChangePayCountDown ~ e:', e)
    },

    // 设置data
    setData(query) {
      // contractId, couponIds, belongType
      const { scene = '', projectId = '', amount = 0, payment = '' } = query
      this.projectId = projectId || ''
      this.scene = scene || ''
      this.amount = amount || 0
      this.payment = payment || ''
      this.orderInfo = { ...query, paymentMethod: payment }
    },

    // 获取支付方式 && 创建预支付订单
    async getData() {
      await this.getPayMethods()
      // await this.createdOrder()
    },

    // 获取可用的支付方式
    async getPayMethods() {
      const params = {
        client_palt: this.$Platform.platform,
        // client_palt: 'ios',
        client_type: 3, // 支付类型 1 APP 2 公众号 3 小程序
        isRenew: 0,
        palt_type: 1, // 主要区分新平台还是老平台 1 老平台 2 新平台
        pay_scene: 5, // 场景 0 不限制 1 账单支付
        proj_id: this.projectId, // 当前支付所属的项目ID
      }
      const { errcode, data = {} } = await getPayChannel(params)
      if (errcode === 0) {
        this.payMethods = data || []
        this.payStatus = 1
      }
    },

    // 创建预支付订单
    async createdOrder() {
      const { errcode, data = {} } = await createdPrePayOrder()
      if (errcode === 0) {
        // this.orderDetail = data
        this.payStatus = 1
      }
    },

    async handlePayment() {
      if (!this.token) return AuthError()

      if (!this.scene) {
        return uni.$uv.toast('支付场景缺失！')
      }
      // if (!(this.amount > 0)) {
      //   return uni.$uv.toast('无效的支付金额！')
      // }
      if (!this.payment) {
        return uni.$uv.toast('请选择支付方式！')
      }
      // 如果scene 为账单切支付金额为0 则进行如下操作
      if (this.scene == 'bill' && (this.amount === '0.00' || this.amount == '0')) {
        const { contractId, belongType, couponId, couponIds } = this.$Route.query
        const coupon_id = couponId ? couponId.split(',') : []
        const coupon_ids = couponIds ? couponIds.split(',') : []
        const { errcode, errmsg } = await billReceiptZreo({ contract_id: contractId, belong_type: belongType, coupon_id, coupon_ids })
        if (errcode === 0) {
          return this.$ROUTE.redirect('/pages/payment/result', { scene: 'bill', payState: 'success' })
        }
      }
      // APP环境的话跳转到小程序去支付
      // #ifdef APP-PLUS
      this.appJumpMP()
      // #endif

      // #ifndef APP-PLUS
      // start 匹配后端入参 支付方式的值为：payment_channel
      const payMethodObj = this.payMethods.find((e) => e.payment_channel_value === this.payment)
      if (payMethodObj) this.orderInfo.paymentMethod = payMethodObj.payment_channel
      else return uni.$uv.toast(`暂不支持${this.payment}此支付方式!`)
      // end

      // 剔除冗余的支付参数
      if (Object.prototype.hasOwnProperty.call(this.orderInfo, 'token')) delete this.orderInfo.token

      this.payStatus = 2
      await this.$Platform.pay(this.payment, this.scene, this.orderInfo)
      // await this.$Platform.pay(this.payment, this.scene, { contractId: '', couponIds: '', belongType: '', paymentMethod: '' })
      this.payStatus = 1
      // #endif
    },

    // #ifdef APP-PLUS
    // APP跳转到小程序
    appJumpMP() {
      const args = this.$Route.options
      if (!args) return this.$uv.toast('支付参数缺失!')

      // 获取分享服务列表
      plus.share.getServices(
        (s) => {
          const { MODE, VITE_WX_MP_GH_ID } = this.DefEnvCon

          const sweixin = s.find((i) => i.id === 'weixin') || null
          // 对象转URL参数
          const argStr = uni.$uv.queryParams({ ...args, payment: this.payment, token: this.token }, true, 'indices')
          sweixin
            ? sweixin.launchMiniProgram(
                {
                  id: VITE_WX_MP_GH_ID, // 要跳转小程序的原始ID
                  path: `/pages/payment/index${argStr}`, // 要跳到的页面支持传参?a=1&b=2
                  type: MODE === 'development' ? 1 : MODE === 'testing' ? 2 : 0, // 微信小程序版本类型 Number:  0-正式版； 1-测试版； 2-体验版。 默认值为0。
                },
                (res) => {
                  // 从MP返回到APP时监听任务回调
                  console.log('🚀 ~ appJumpMP ~ res:', res)
                  // 支付完成直接跳转到支付结果页
                  if (res) this.$ROUTE.redirect('/pages/payment/result', JSON.parse(res))
                },
                (err) => {
                  console.log('🚀 ~ appJumpMP ~ err:', err)
                },
              )
            : uni.$uv.toast('当前环境不支持微信操作!')
        },
        (e) => {
          console.log('获取分享服务列表失败：' + e.message)
        },
      )
    },
    // #endif
  },
}
</script>

<style lang="scss" scoped>
page {
  background: #f2f8f8 !important;
}
.#{prefixCls('payment-container')} {
  position: relative;
  .bill-detail {
    width: 100%;
    padding: 35px 0;
    background: white;
    text-align: center;
    .bill-detail-title {
      color: #999999;
    }
    .bill-detail-price {
      margin-top: 30rpx;
      font-size: 36rpx;
      font-weight: bold;
      text {
        font-size: 26rpx;
      }
    }
    .bill-detail-time {
      margin-top: 30rpx;
      font-size: 28rpx;
      color: $uv-main-color;
    }
  }
  .payment-method {
    margin-top: 20rpx;
    padding: 0 15px;
    background: white;
    display: flex;
    flex-direction: column;
    ::v-deep .uv-radio {
      padding: 15px 0;
      border-bottom: 1px solid #f5f5f5;
    }
    .payment-method-item {
      display: flex;
      align-items: center;
      image {
        background: #f5f5f5;
        width: 25px;
        height: 25px;
        margin-right: 10px;
      }
    }
    // flex-wrap: wrap;
  }
  .payment-btn {
    position: fixed;
    width: 100%;
    box-sizing: border-box;
    background: white;
    padding: 10px 15px;
  }
}
</style>
